package com.diandiansong.app.ui.index;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.ImageView;

import com.diandiansong.app.R;
import com.diandiansong.app.entity.NewsInfo;
import com.diandiansong.app.ui.base.BaseAct;
import com.diandiansong.app.utils.A;
import com.diandiansong.app.utils.Api;

import java.util.List;

import diandiansong.library.ui.base.FastListFragment;
import diandiansong.library.utils.CCallBack;
import diandiansong.library.utils.ImgLoader;

/**
 * 新闻资讯
 */
public class NewsList extends BaseAct {

    public static void start(Context context) {
        Intent starter = new Intent(context, NewsList.class);
        context.startActivity(starter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        initTitle("新闻资讯");

        addFragment(new SubFragment());
    }

    public static class SubFragment extends FastListFragment {
        @Override
        public int getItemLayoutRes() {
            return R.layout.news_item;
        }

        @Override
        public void bindItemView(int position, @NonNull View convertView) {
            NewsInfo.Data item = (NewsInfo.Data) getItem(position);

            ImageView iv = findViewById(convertView, R.id.iv_news_cover);


            ImgLoader.display(iv, item.getTitleImg());

            fastText(convertView, R.id.tv_news_date, item.getCreatetime());
            fastText(convertView, R.id.tv_news_title, item.getTitle());
        }

        /**
         * 滑到底部时调用
         */
        @Override
        protected void loadMore() {
            A.news(mPage, new CCallBack<NewsInfo>() {
                @Override
                public void onSuccess(NewsInfo o) throws Exception {
                    List<NewsInfo.Data> data = o.getData();
                    if (mPage.equals("0")) {
                        mAdapter.setData(data);
                    } else {
                        mAdapter.addAll(data);
                    }
                    if (mAdapter.getDataSize() > 0) {
                        mPage = ((NewsInfo.Data) getLast()).getId();
                    }
                    onLoadFinishHasMore(data.size() >= Api.PAGE_SIZE);
                }

                @Override
                public void onFailure(int code, String msg) {
                    onLoadFinishNoMore();
                    toast(msg);
                }
            });
        }

        @Override
        public void onItemClick(Object o) {
            super.onItemClick(o);
            NewsInfo.Data item = (NewsInfo.Data) o;
            Web.start(getActivity(), Api.URL + "/app/news_view?id=" + item.getId());
        }
    }
}
